package com.huang;

import com.huang.realm.MD5Realm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import javax.tools.Tool;
import java.util.Arrays;

public class TestCustomerMd5Realm {
    public static void main(String[] args) {
        DefaultSecurityManager manager = new DefaultSecurityManager();

        MD5Realm realm = new MD5Realm();
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();//修改密码验证规则md5
       matcher.setHashIterations(1024);//使用了随机盐 和hash散列需要告诉匹配器 散列次数
        matcher.setHashAlgorithmName("md5");
        realm.setCredentialsMatcher(matcher);

        manager.setRealm(realm);
        SecurityUtils.setSecurityManager(manager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("xiaohuang","123");

        try {
            subject.login(token);
            System.out.println("登陆成功");
            System.out.println(subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("账号出错");
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }
        //判断是否认证  进行授权
        if(subject.isAuthenticated()){
            //基于角色的权限控制
            System.out.println(subject.hasRole("admin"));
            for (boolean b : subject.hasRoles(Arrays.asList("user", "admin", "super"))) {
                System.out.println(b);
            }
            System.out.println("================");
            System.out.println(subject.hasAllRoles(Arrays.asList("user","admin")));
            //
            System.out.println("权限"+subject.isPermitted("user:*:01"));
        }
    }
}
